﻿using GameProject.Models;
using GameProject.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace GameProject.Controllers
{
	public class Connect4Controller : Controller
	{
		private GameInstanceService gameService = new GameInstanceService();

		/// <summary>
		/// Returns the view for the game, Connect 4
		/// </summary>
		/// <returns>View</returns>
		[Authorize]
		public ActionResult Index()
		{
			return View();
		}

		/// <summary>
		/// Returns the view for the site with the Connect 4 game rules
		/// </summary>
		/// <returns>View</returns>
		public ActionResult C4GameRules()
		{
			return View();
		}

		/// <summary>
		/// Shows a list of connect4 games
		/// </summary>
		/// <returns>View with active games</returns>
		public ActionResult GameList()
		{
			List<GameInstance> activeGames = gameService.GetWaitingGames().Where(x => x.GameType != null && x.GameType.ID == 2).ToList();
			return View(activeGames);
		}

		/// <summary>
		/// Returns the view for the create game site. Expected number of players is hardcoded 2
		/// </summary>
		/// <returns>View</returns>
		[Authorize]
		public ActionResult CreateGame()
		{
			GameInstance game = new GameInstance() { ExpectedNumberOfPlayers = 2 };

			return View(game);
		}

		/// <summary>
		/// POST function to create a game
		/// </summary>
		/// <param name="game">The game being played</param>
		/// <returns>The site with the matching game ID or if it fails, the View for create game</returns>
		[Authorize]
		[HttpPost]
		public ActionResult CreateGame(GameInstance game)
		{

			if (ModelState.IsValid)
			{
				//Gets the game with the ID = 2, e.g. Connect4
				GameType gameType = gameService.GetGameTypeById(2);
				game.GameType = gameType;
				//Adds the game and saves it to the database
				gameService.AddGameInstance(game);
				gameService.Save();

				game.Grid = new Grid();
				game.Grid.Cells = new List<GridCell>();

				for (int i = 1; i <= 42; i++)
				{
					GridCell newCell = new GridCell();
					newCell.status = 0;
					newCell.index = i;
					game.Grid.Cells.Add(newCell);

				}
				gameService.Save();

				return RedirectToAction("Index", new { id = game.ID });
			}
			else
			{
				return View();
			}
		}
	}
}
